// @ts-check

// Run via: pnpm run --filter=typescript-sandbox bootstrap

// Ensure the versions dropdown is up to date
const { writeFileSync } = require("fs")
const { join } = require("path")
const { format } = require("prettier")

const go = async () => {
  const response = await fetch("https://playgroundcdn.typescriptlang.org/indexes/releases.json")
  const releases = await response.json()
  const versions = releases.versions.reverse()

  // Look through the prereleases to see if the beta and RC are included in the pre-releases
  // and add those to the list of versions.
  const preReleaseResponse = await fetch("https://playgroundcdn.typescriptlang.org/indexes/pre-releases.json")
  const preReleases = await preReleaseResponse.json()
  const latestStable = versions[0]

  // e.g. 4.3.1 -> 4.4.0-beta
  // this won't work for 5.0 specifically, but that's an ok edge case for me
  const possibleBeta = `${latestStable.split(".")[0]}.${Number(latestStable.split(".")[1]) + 1}.0-beta`
  const addBeta = preReleases.versions.includes(possibleBeta)

  const possibleRc = `${latestStable.split(".")[0]}.${Number(latestStable.split(".")[1]) + 1}.1-rc`
  const addRc = preReleases.versions.includes(possibleRc)

  // Get the highest maj/min ignoring patch versions
  const latestMajMin = new Map()
  versions.forEach(v => {
    const majMin = v.split(".")[0] + "." + v.split(".")[1]
    if (!latestMajMin.has(majMin)) {
      latestMajMin.set(majMin, v)
    }
  })

  // prettier-ignore
  // Adds RC and Beta to the versions automatically
  const supportedVersions = [
    addRc ? possibleRc : "", 
    addBeta ? possibleBeta : "", 
    ...latestMajMin.values()
  ].filter(Boolean)

  const code = `// This is auto-generated by scripts/downloadReleases.js
/** Every prod version **/
export const allReleases = ["${versions.join('", "')}"] as const

/** The latest major.min version **/
export const supportedReleases = ["${supportedVersions.join('", "')}"] as const

/** A type of all versions **/
export type ReleaseVersions = "${[possibleBeta, possibleRc, ...versions].join('" | "')}"
`
  const path = join(__dirname, "..", "src", "release_data.ts")
  writeFileSync(path, format(code, { filepath: path }), "utf8")

  const jsonPath = join(__dirname, "..", "src", "releases.json")
  writeFileSync(jsonPath, format(JSON.stringify(releases), { filepath: jsonPath }), "utf8")
  console.log("Updated the releases with the versions created by make-monaco-builds")
}

go()
